const express = require("express");
const router = express.Router();
const useApiRes = require('../common/apiRes')
const { WWW_PATH, APP_DEBUG } = require('../../tools/helper');
const axios = require("axios");
const path = require("path");
const fs = require("fs");

const useCommonFun = require("../common");
// 获取HTML
router.get("/download", async (req, res) => {
    const fontDownloadUrl = 'https://ecloud.yzhkj.cn/inv/fonts'
    let total = 0;
    let okNum = 0;
    let errNum = 0
    const fontPath = path.join(WWW_PATH, 'fonts')
    if (!fs.existsSync(fontPath)) {
        fs.mkdirSync(fontPath, { recursive: true });
    }
    try {
        const response = await axios({
            method: 'get',
            url: fontDownloadUrl,
            headers: {
                'Content-Type': 'application/json'
            },
            timeout: 3000,
            responseType: 'json'
        });
        const { data } = response
        const list = data.data.list
        total = list.length
        if (list) {
            list.forEach(async item => {
                const filePath = path.join(fontPath, item.name);
                if(APP_DEBUG){
                    console.log('filePath', filePath)
                }
                if (!fs.existsSync(filePath)) {
                    await useCommonFun.downloadByUrl(filePath, item.url).then(res => {
                        okNum += 1
                    }).catch(err => {
                        errNum += 1
                    })
                } else {
                    okNum += 1
                    if (APP_DEBUG) {
                        console.log("字体已存在！", filePath)
                    }
                }
            });
        }
        const result = {
            total: total,
            okNum: okNum,
            errNum: errNum
        }
        return useApiRes.success(res, result);
    } catch (err) {
        return useApiRes.fail(res, err.message);
    }
})

module.exports = router;